package NC;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;

public class NC15 {
    public ArrayList<ArrayList<Integer>> levelOrder (TreeNode root) {
        if(root==null) return new ArrayList<>();
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        ArrayList<ArrayList<Integer>> ans = new ArrayList<>(); //临时存放取出的值，用于逆序输出

        while (!queue.isEmpty()){
            ArrayList<Integer> list = new ArrayList<>(); //临时存放取出的值，用于逆序输出
            int size = queue.size();//现在在队伍中还有几个元素
            for (int i = 0; i < size; i++) {
                TreeNode node  = queue.poll();
                list.add(node.val);
                if(node.left!=null) queue.offer(node.left);
                if(node.right!=null) queue.offer(node.right);

            }
            ans.add(list);
        }
        return ans;
    }
}
